Reverse Integer
August 19, 2016
This one was had me stumped for a while. My first solution was similar to the one below, but I first found the size of the int by using
(int)(Math.log(x)/Math.log(10))+1;
LeetCode kept giving me a TimeRanOut Error everytime I tried to do the above, so I had to develop the below solution. In addition, accounting for numbers beyond the scope of an int became a bit tricky to solve.
Full Solution in Java:
public class Solution { public int reverse(int x) { long result = 0; while(x!=0){ result = result*10+ x%10; x/=10; } if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){ return 0; } return (int)result; } }